<?php


namespace app\api\controller\v9;


use app\api\controller\v2\Auth;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\SystemConfig;
use app\common\cachemodel\ZhunleActivity;
use app\common\lib\Natal;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Env;
use think\response\Json;

class NatalReport extends Auth
{
    /**
     * 本命预测
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function index()
    {
        $rid = input('rid/d', 0);
        $uid = $this->user['id'];

        $recodeModel = new Recode();
        $NatalReportModel = new \app\common\cachemodel\NatalReport();
        if ($rid)
        {
            $recodeInfo = $recodeModel->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '档案不存在');
            }
        } else
        {
            $recodeInfo = $recodeModel->getSelfRecode(['uid' => $this->user['id']]);
            if (!$recodeInfo)
            {
                return show(config('code.error'), '档案不存在');
            }
            $rid = $recodeInfo['id'];
        }
        //  获取系统配置
        $config = (new SystemConfig())->getSystemConfig(['title1', 'title_intro1', 'title2', 'title_intro2']);
        //  获取分数及词条
        $natal = (new Natal())->getScoreAndText($recodeInfo);
        //  获取本命预测商品信息
        $goodData = (new NatalGoods())->getGoods();
        // 获取解锁订单信息状态
        $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
        // $unlockReport = $NatalReportModel->getNatalReport($uid, $rid);

        $forecast = [];
        $unlocking = [];
        $active = [];
        $lock = [];
        $unopened = [];
        $unlock = [];
        $orderModel = new \app\common\cachemodel\Orders();

        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];
        foreach (array_values($goodData) as $key => $item)
        {
            if ($item['status'] == 2)//暂不开放状态
            {
                $status = 3;
            } else//判断商品解锁状态
            {
                if (isset($unlockReport[$item['id']]))
                {
                    $unlock_status = (int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1;
                    $status = isset($unlockReport[$item['id']]) ? ($unlock_status) : 0;
                } else
                {
                    $status = 0;
                }
            }
            $d = [
                'gid' => (int)$item['id'],
                'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                'text' => $natal[$oldNatalScore[$item['flag']] . '_text'] ?? '',
                'status' => $status,
                'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                'bg_img' => $item['bg_img'] ?? '',
                'title_img' => $item['title_img'] ?? '',
                'unlock_num' => $item['base_num'] + $orderModel->getTotalPrepaidOrder(7, $item['id']),
                'intro' => $item['intro'] ?? '',
                'gcolor' => $item['color'] ?? '',
//                'gname' => $this->gidName[$item['flag']] ?: '',
                'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
//                'active_time' => $item['active_time']
                'active_time' => 0
            ];

            if ($d['status'] == 1)
            {   // 解锁中
                $unlocking[] = $key;
            } elseif ($d['status'] == 0 && $d['active_time'] > 0)
            {   // 限时特价 并且 未解锁
                $active[] = $key;
            } elseif ($d['status'] == 0)
            {   // 未解锁
                $lock[] = $key;
            } elseif ($d['status'] == 3)
            {
                //未开放
                $unopened[] = $key;
            } else
            {   // 已解锁
                $unlock[] = $key;
            }
            $forecast[] = $d;
        }

        $data = [
            'title1' => (isset($config['title1']) && !empty($config['title1'])) ? $config['title1'] : '',
            'title_intro1' => (isset($config['title_intro1']) && !empty($config['title_intro1'])) ? $config['title_intro1'] : '',
            'title2' => (isset($config['title2']) && !empty($config['title2'])) ? $config['title2'] : '',
            'title_intro2' => (isset($config['title_intro2']) && !empty($config['title_intro2'])) ? $config['title_intro2'] : '',
            'sort_index' => array_merge($active, $unlock, $unlocking, $lock, $unopened),
            'forecast_list' => $forecast,
            'page_title' => '一生报告'
        ];
        return show(config('code.success'), '一生报告', $data);
    }

    /**
     * 报告详情
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function detail()
    {
        $gid = input('gid/d', 0);
        if (!in_array($gid, [39, 40, 41, 42, 52], true))
        {
            return show(config('code.error'), '未知的商品');
        }
        $rid = input('rid/d', 0);
        if (!$rid && !$this->user['rid'])
        {
            return show(406, '档案缺失，去添加档案');
        }
        $rid = $rid ?: $this->user['rid'];
        $uid = $this->user['id'];

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        if (!$gid) return show(config('code.error'), '请求异常');

        //获取商品类型
        $goodData = (new NatalGoods())->getGoods();
        // 判断当前解锁状态
        $unlockReport = (new \app\common\cachemodel\NatalReport())->getNatalReport2($recode);
        // $unlockReport = (new \app\common\cachemodel\NatalReport())->getNatalReport($uid, $rid);

        if ($unlockReport && isset($unlockReport[$gid]) && $unlockReport[$gid]['status'] == 2)
        {   // 解锁成功
            $gname = '';
            foreach ($goodData as $key => $item)
            {
                if ($item['id'] == $gid)
                {
                    $gname = $item['name'];
                    break;
                }
            }
            $result = [
                'status' => 2,
                'url' => Env::get('host.domain') . '/web/natal_report/index?gid=' . $gid . '&rid=' . $rid,
                'gname' => $gname
            ];
        } else
        {   // 未解锁 或 解锁中
            $orderModel = new \app\common\cachemodel\Orders();
            $status = isset($unlockReport[$gid]) ? ($unlockReport[$gid]['status'] == 2 ? 2 : 1) : 0;
            $unlockingData = [];
            $activeData = [];
            $lockData = [];
            $unlockData = [];
            $gname = '';
            $textNum = 0;
            $unlockNum = 0;
            $headerBg = '';
            $contentBg = '';
            $natalReportPrice = [];
            $activingModel = new ZhunleActivity();
            $utilLib = new Util();
            foreach ($goodData as $key => $item)
            {
                $unlockNumber = $orderModel->getTotalPrepaidOrder(7, $item['id']);
                // 获取活动商品信息
                $activing = $activingModel->getActivingGood(7, $item['id']);
                if ($activing)
                {
                    $actiGids = explode(',', $activing['gids']);
                    if (in_array($gid, $actiGids, false))
                    {
                        $discount_price = sprintf('%.2f', $item['now_prize'] * $activing['attr']);
                    }
                    $timeRange = $activing['end_time'] - time();
                }
                if ($item['id'] == $gid)
                {
                    $natalReportPrice = [
//                        'or_price' => $item['or_prize'],
                        'now_price' => $discount_price ?? $item['now_prize'],//todo 改为活动折扣描述，例如：限时九折 仅179
                        'active_time' => $timeRange ?? 0,
                    ];
                    $gname = $item['name'];
                    $unlockNum = $item['base_num'] + $unlockNumber;
                    $textNum = $item['text_num'];
                    $headerBg = $item['header_bg'];
                    $contentBg = $item['content_bg'];
                } else
                {
                    if ($item['status'] != 2)
                    {
                        if (isset($unlockReport[$item['id']]))
                        {
                            if ($unlockReport[$item['id']]['status'] == 2)
                            {
                                $unlock_status = 2;//已解锁
                            } else
                            {
                                $unlock_status = 1;//计算中
                            }
                        } else
                        {
                            $unlock_status = 0;//未解锁
                        }
                    } else
                    {
                        $unlock_status = 3;//未开放
                    }

                    $d = [
                        'gid' => (int)$item['id'],
                        'status' => $unlock_status,
                        'bg_img' => $item['bg_img'] ?? '',
                        'title_img' => $item['title_img'] ?? '',
                        'unlock_num' => $item['base_num'] + $unlockNumber,
                        'intro' => $item['intro'] ?? '',
                        'active_time' => $timeRange ?? 0,
                    ];

                    if ($d['status'] == 1)
                    {   // 解锁中
                        $unlockingData[] = $d;
                    } elseif ($d['status'] == 0 && $d['active_time'] > 0)
                    {   // 限时特价 并且 未解锁
                        $activeData[] = $d;
                    } elseif ($d['status'] == 0)
                    {   // 未解锁
                        $lockData[] = $d;
                    } elseif ($d['status'] == 2)
                    {   // 已解锁
                        $unlockData[] = $d;
                    }
                }
            }

            $result = [
                'gname' => $gname,
                'status' => (int)$status,
                'text_num' => (int)$textNum,
                'unlock_num' => (int)$unlockNum,
                'header_bg' => $headerBg,
                'content_bg' => $contentBg,
                'natal_report_list' => array_merge($activeData, $unlockData, $unlockingData, $lockData),
                'natal_report_price' => $natalReportPrice
            ];
        }

        return show(config('code.success'), '请求成功', $result);
    }
}
